<template>
  <div class="freightDiv">
    <el-card class="form-container" shadow="never" style="border:0;width:1200px">
      <el-form :model="freight" :rules="rules" ref="freightFrom" label-width="150px">
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="freight.shopName" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="计费方式">
          <el-radio-group v-model="freight.chargeMode">
            <el-radio :label="1" border>按件数</el-radio>
            <el-radio :label="0" border>按重量</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配送区域及运费">
          <el-table border :data="deliveryRules">
            <el-table-column label="可配送区域" width="608" align="center">
              <template slot-scope="scope">
                {{scope.row.cityStr}}
                <p align="right">
                  <el-button
                    type="primary"
                    @click="editRule(scope.$index)"
                    icon="el-icon-edit"
                    circle
                    plain
                  ></el-button>
                  <el-button
                    type="danger"
                    @click="deleteRule(scope.$index)"
                    icon="el-icon-delete"
                    circle
                    plain
                  ></el-button>
                </p>
              </template>
            </el-table-column>
            <el-table-column label="首件(个)" width="100" align="center">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.first">{{scope.row.first}}</el-input>
              </template>
            </el-table-column>
            <el-table-column label="运费(元)" width="100" align="center">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.firstFree">{{scope.row.firstFree}}</el-input>
              </template>
            </el-table-column>
            <el-table-column label="续件(个)" width="100" align="center">
              <template slot-scope="scope">
                <el-input size="mini" v-model="scope.row.additional">{{scope.row.additional}}</el-input>
              </template>
            </el-table-column>
            <el-table-column label="运费(元)" width="100" align="center">
              <template slot-scope="scope">
                <el-input
                  size="mini"
                  v-model="scope.row.additionalFree"
                >{{scope.row.additionalFree}}</el-input>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 20px">
            <el-button icon="el-icon-location-outline" @click="addRule()">添加配送区域</el-button>
          </div>
        </el-form-item>
        <el-form-item label="排序：" prop="templateSort">
          <el-input v-model.number="freight.templateSort" style="width:300px">></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit('brandFrom')">提交</el-button>
          <el-button v-if="!isEdit" @click="resetForm('brandFrom')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog
      title="选择可配送区域"
      :visible.sync="dialogVisible"
      width="750px"
      :before-close="handleClose"
    >
      <div class="el-dialog-div">
        <el-checkbox v-model="checkAll" @change="checkedAllChange" />全选
        <el-tree
          :data="cities"
          show-checkbox
          node-key="code"
          ref="cityTree"
          :props="defaultProps"
          check-on-click-node
          @check-change="handleCheckChange"
        ></el-tree>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import api from "@/http";
const defaultfreight = {
  chargeMode: null,
  shopId: null,
  shopName: null,
  templateId: null,
  templateName: null,
  templateSort: null
};
const defaultDeliveryRule = {
  citys: null,
  first: null,
  firstFree: null,
  additional: null,
  additionalFree: null,
  cityStr: null
};
export default {
  name: "FreightDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultProps: {
        children: "city",
        label: "name"
      },
      editRuleIndex:-1,
      defaultCities: [],
      allCityCount: 0,
      dialogVisible: false,
      checkAll: false,
      cities: [], //待选城市
      freight: Object.assign({}, defaultfreight),
      deliveryRules: [],
      rules: {
        shopName: [{ required: true, message: "请选择店铺", trigger: "blur" }],
        sort: [{ type: "number", message: "排序必须为数字" }]
      }
    };
  },
  created() {
    if (this.isEdit) {
      this.$api.freight.info(this.$route.query.id).then(response => {
        this.freight = response.data
        this.deliveryRules = response.data.deliveryRules
      });
    } else {
      this.freight = Object.assign({}, defaultfreight)
    }
    //获取城市数据
    this.$api.city.fetchList().then(response => {
      this.cities = response.data
      this.allCityCount = this.cities.length
      this.cities.forEach(element => {
        if (element.city) {
          this.allCityCount += element.city.length
          element.cityNum = element.city.length
        }
      })
      this.defaultCities = Object.assign([], this.cities)
    })
  },
  methods: {
    editRule(index) {
      this.editRuleIndex=index
      this.cities = Object.assign([], this.defaultCities)
      let rules = Object.assign([], this.deliveryRules)
      let rule = rules[index]
      let ruleOther = []
      rules.forEach((r, i) => {
        if (i!=index) {
          ruleOther.push(r)
        }
      })
      console.log(ruleOther)

      if (ruleOther.length == 0) {
         this.$refs.cityTree.setCheckedKeys(rule.citys)
         this.dialogVisible = true
         return
      }
      //获取选中的，不包括自己的
      let removeCity = []
      ruleOther.forEach(ci => {
        removeCity = removeCity.concat(ci.citys)
      });
      //删除节点，保留原节点数据

      let checkCity=[]
      this.cities.forEach(province => {
        let delCount = 0
        if (province.city) {
          province.city.forEach(ci => {
            removeCity.forEach(rci => {
              if (rci == ci.code) {
                delCount++
                province.city = province.city.filter(item => {
                  return item.code != rci
                })
              }
            })

            //同时取rule里的城市部分，不取省
            rule.citys.forEach(cci=>{
              if(ci.code==cci)
              {
                checkCity=checkCity.concat(cci)
              }
            })

          })
          if (delCount == province.cityNum) {
            this.cities = this.cities.filter(item => {
              return item.code !== province.code
            })
          }
        } else {
          removeCity.forEach(rci => {
            if (province.code == rci) {
              this.cities = this.cities.filter(item => {
                return item.code !==province.code
              })
            }
          })
        }
      })

      this.$refs.cityTree.setCheckedKeys(checkCity)
      this.dialogVisible = true
    },
    addRule() {
      this.editRuleIndex=-1
      this.checkAll = false
      //所有已选择的
      let checkCity = []
      let checkCount = 0
      this.deliveryRules.forEach(ci => {
        if (ci.citys) {
          checkCity = checkCity.concat(ci.citys)
          checkCount += ci.citys.length
        }
      });

      if (checkCount >= this.allCityCount) {
        this.$message({
          message: "您已选择了全部地区",
          type: "warning",
          duration: 1000
        });
        this.dialogVisible = false;
        return false
      } else if (checkCount > 0) {
        //删掉已选择的
        //循环省
        this.cities.forEach((province, pindex) => {
          if (province.city) {
            //循环市
            var cityCount = province.city.length;
            var delCount = 0
            province.city.forEach((ci, cindex) => {
              checkCity.forEach(cci => {
                if (cci == ci.code) {
                  delCount = delCount + 1
                  province.city = province.city.filter(item => {
                    return item.code != cci
                  });
                }
              });
            });
            if (delCount == cityCount) {
              this.cities = this.cities.filter(item => {
                return item.code != province.code
              });
            }
          } else {
            checkCity.forEach(cci => {
              if (province.code == cci) {
                this.cities = this.cities.filter(item => {
                  return item.code != province.code
                });
              }
            });
          }
        });
        this.$refs.cityTree.setCheckedKeys([])
      }

      this.dialogVisible = true
    },
    deleteRule(index) {
      this.$confirm("确认要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deliveryRules.splice(index, 1);
          this.$message({
            type: "warning",
            message: "已删除，稍后请保存!"
          });
        })
        .catch(() => {})
    },
    handleClose(done) {
      done();
    },
    confirmDo() {
      let rule = Object.assign({}, defaultDeliveryRule); //复制新对象
      rule.citys = this.$refs.cityTree.getCheckedKeys();
      if (rule.citys.length == 0) {
        this.dialogVisible = false
        return
      }
      if (rule.citys.length == this.allCityCount) {
        rule.cityStr = "全国"
      } else {
        let cityName = ""
        this.cities.forEach(province => {
          let cityTemp = ""
          let cityCount = 0
          let hasCity = false
          if (!province.city) {
            rule.citys.forEach(item => {
              if (province.code == item) {
                cityName += province.name + ","
              }
            });
            return true;
          }
          province.city.forEach(pci => {
            rule.citys.forEach(ci => {
              if (pci.code == ci) {
                cityTemp += pci.name + ","
                hasCity = true
                cityCount++
              }
            });
          });
          if (hasCity && cityCount != province.cityNum) {
            cityName += province.name + "(" + cityTemp + ")"
          } else if (hasCity && cityCount == province.cityNum) {
            cityName += province.name + ","
          }
        });
        rule.cityStr = cityName
      }

      if(this.editRuleIndex>-1)
      {
        this.deliveryRules[this.editRuleIndex]=rule

      }
      else
      {
        this.deliveryRules.push(rule)
      }


      this.dialogVisible = false
    },
    checkedAllChange() {
      if (this.checkAll) {
        //全选
        this.$refs.cityTree.setCheckedNodes(this.cities);
      } else {
        //取消选中
        this.$refs.cityTree.setCheckedKeys([])
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      let len = this.$refs.cityTree.getCheckedNodes().length
      if (len == this.allCityCount) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    }
  }
};
</script>
<style>
.freightDiv .el-table__header tr,
.freightDiv .el-table__header th {
  padding: 0;
  height: 25px;
}
.el-dialog-div {
  height: 60vh;
  overflow: auto;
}
</style>



